package yi.wuhenbot.Controller;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import yi.wuhenbot.Service.BotRequest;
import yi.wuhenbot.Service.BotService;
import yi.wuhenbot.Utils.BotTokenUtil;

import yi.wuhenbot.config.BotConfig;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import yi.wuhenbot.entity.Payload;
import yi.wuhenbot.entity.BotValidationRequest;
import yi.wuhenbot.entity.BotValidationResponse;


import java.nio.charset.StandardCharsets;
import java.security.KeyPair;

import java.security.Security;
import java.util.Collections;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Set;

import static yi.wuhenbot.Utils.SigUtils.*;


/**
 * 机器人webhook接口
 * @author wuhen
 */
@RestController
@RequestMapping("/webhook")
public class BotController {
    @Autowired
    private BotService botService;

    @Autowired
    private BotTokenUtil botTokenUtil;
    @Autowired
    private BotRequest botRequest;

    @Value("${bot.webhook}")
    private boolean webhook;

    private static BotController botController;

    @PostConstruct
    public void init() {
        botController = this;
    }

    private  static final  String C2C_MESSAGE_CREATE = "C2C_MESSAGE_CREATE";
    private  static final  String GROUP_AT_MESSAGE_CREATE = "GROUP_AT_MESSAGE_CREATE";
    private  static final  String AT_MESSAGE_CREATE = "AT_MESSAGE_CREATE";
    private  static final  String DIRECT_MESSAGE_CREATE = "DIRECT_MESSAGE_CREATE";



    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(BotController.class);
    private static final Set<String> processedEvents = Collections.synchronizedSet(new HashSet<>());

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @PostMapping
    public ResponseEntity<?> handleValidation(@RequestBody String rawBody,
                                              @RequestHeader("X-Signature-Ed25519") String sig,
                                              @RequestHeader("X-Signature-Timestamp") String timestamp) {
        // 获取参数op
        Integer op = JSON.parseObject(rawBody, Payload.class).getOp();
        String t = JSON.parseObject(rawBody, Payload.class).getT();
        logger.info("收到op：{}", op);
        logger.info("收到事件类型：{}", t);
        //logger.info("收到原始body：{}", rawBody);

        try {
            String seed = prepareSeed(BotConfig.APP_SECRET);
            KeyPair keyPair = generateEd25519KeyPair(seed.getBytes(StandardCharsets.UTF_8));
            Payload<?> payload = JSON.parseObject(rawBody, Payload.class);
            // 每个事件唯一id 在配置回调地址时禁用，要保证连接通过
            if (webhook) {
                String eventId = payload.getId();
                if (processedEvents.contains(eventId)) {
                    logger.info("事件已处理，跳过: {}", eventId);
                    return ResponseEntity.ok(true);
                }
                processedEvents.add(eventId);
            }


            switch (payload.getOp()) {
                case 0 -> {
                    boolean isValid = verifySignature(sig, timestamp, rawBody.getBytes(StandardCharsets.UTF_8), keyPair.getPublic().getEncoded());
                    // 判断消息来源(私聊/群聊/频道/频道私信)
                    if (t.equals(C2C_MESSAGE_CREATE)) {
                        logger.info("私聊消息");
                        // 处理机器人逻辑
                        botRequest.handlePrivateMessageTest(rawBody);
                    } else if (t.equals(GROUP_AT_MESSAGE_CREATE)) {
                        logger.info("群聊消息");
                        // 处理机器人逻辑
                        botRequest.handleGroupMessageTest(rawBody);
                    } else if (t.equals(AT_MESSAGE_CREATE)) {
                        logger.info("频道消息");
                        // 处理机器人逻辑
                        botRequest.handleChannelMessageTest(rawBody);
                    } else if (t.equals(DIRECT_MESSAGE_CREATE)) {
                        logger.info("直接消息");
                        // 处理机器人逻辑
                        botRequest.handleDirectMessageTest(rawBody);
                    }
                    return ResponseEntity.ok(isValid);
                }
                case 13 -> {
                    //验证签名
                    logger.info("验证有效性...");
                    BotValidationRequest validationPayload = objectMapper.convertValue(payload.getD(), BotValidationRequest.class);
                    byte[] message = (validationPayload.getEvent_ts() + validationPayload.getPlain_token()).getBytes(StandardCharsets.UTF_8);
                    byte[] signature = signMessage(keyPair.getPrivate(), message);
                    BotValidationResponse resp = new BotValidationResponse(validationPayload.getPlain_token(), HexFormat.of().formatHex(signature));
                    logger.info("验证成功");
                    return ResponseEntity.ok(resp);
                }
                default -> logger.info("未处理操作：" + JSON.toJSONString(payload));
            }
        } catch (Exception e) {
            logger.error("验证失败：", e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(false);
    }



    /**
     * 获取机器人token
     * @return 机器人token
     */
    @GetMapping("/getToken")
    public String getToken() {
        return botTokenUtil.getToken();
    }


}
